<template>
  <edit-layout ref="layout" :page="page" :form="form" @invoke="invoke">
    <el-form
      ref="form"
      :model="form"
      :size="page.settings.formSize"
      :label-width="page.settings.labelWidth"
    >
      <!-- 添加 -->
      <div v-if="form!=null && form.id===null">
        <el-row v-if="!iswaiDiaoChe">
          <el-col v-if="!isLogisticsDirector" :span="8">
            <el-form-item label="驾驶员" prop="creatorId">
              <form-remote-select
                v-model="form.creatorId"
                :url="$http.conf.api.get('wms').url+'/api/logistics/driver/map/1'"
                :disabled="isLogisticsDirector"
                @change="driverChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车辆" prop="carId" :rules="page.rules.def">
              <form-remote-select
                v-model="form.carId"
                :url="$http.conf.api.get('wms').url+'/api/logistics/car/map/1'"
                @change="selectCar"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="挂车车牌" prop="semitrailerNo">
              <el-input v-model="form.semitrailerNo" class="col-8" placeholder="挂车车牌" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="纸厂单号" prop="pageNo">
              <el-input v-model="form.pageNo" class="col-8" placeholder="纸厂单号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider />
        <el-row v-if="!iswaiDiaoChe">
          <el-col :span="8">
            <el-form-item label="运输类型" prop="lineType">
              <el-radio v-model="form.lineType" :label="0">直达</el-radio>
              <el-radio v-model="form.lineType" :label="1">回头</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运输类型" prop="originType">
              <el-radio v-model="form.originType" :label="0">采购</el-radio>
              <el-radio v-model="form.originType" :label="1">其他</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 外调车信息 -->
        <el-divider />
        <el-row v-if="iswaiDiaoChe">
          <el-col :span="8">
            <el-form-item label="外调车车牌" prop="carNo" :rules="page.rules.def">
              <el-input v-model="form.carNo" class="col-8" placeholder="车牌" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="外调半挂车车牌" prop="semitrailerNo">
              <el-input v-model="form.semitrailerNo" class="col-8" placeholder="外调半挂车车牌" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="外调车联系方式" prop="carPhone" :rules="page.rules.def">
              <el-input v-model="form.carPhone" class="col-8" placeholder="外调车联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="发货地地区" prop="startArea" :rules="page.rules.def">
              <form-area
                v-model="form.startAreaIds"
                class="col-3"
                :area="form.startArea"
                :level="3"
                @set-area="setAreaStart"
              />
              <el-badge value="address" class="item">
                <el-button @click="UsualAddressUesd('start')">常用地址</el-button>
              </el-badge>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发货地地址" prop="startAddress" :rules="page.rules.def">
              <el-input
                v-model="form.startAddress"
                type="textarea"
                class="col-8"
                placeholder="请输入详情地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider />
        <el-row>
          <el-col :span="8">
            <el-form-item label="目的地地区" prop="endArea" :rules="page.rules.def">
              <form-area
                v-model="form.endAreaIds"
                class="col-24"
                :area="form.endArea"
                :level="3"
                @set-area="setAreaEnd"
              />
              <el-badge value="address" class="item">
                <el-button @click="UsualAddressUesd('end')">常用地址</el-button>
              </el-badge>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="目的地地址" prop="endAddress" :rules="page.rules.def">
              <el-input
                v-model="form.endAddress"
                type="textarea"
                class="col-8"
                placeholder="请输入详情地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注：" prop="remark">
          <el-input
            v-model="form.remark"
            class="col-8"
            type="textarea"
            :rows="4"
            placeholder="备注信息"
          />
        </el-form-item>
      </div>
      <!-- 修改 -->
      <div v-if="form.id!=null">
        <div v-if="form.status!=-1" class="bb20 w120">
          <el-form-item label="运单状态:" prop="status">
            <el-steps :active="form.status" finish-status="success" :space="200">
              <el-step
                v-for="item in constants.logisticsOrderSuccessStatus.values()"
                :key="item.value"
                :title="item.label"
                :value="item.value"
              />
            </el-steps>
          </el-form-item>
        </div>
        <el-divider content-position="left">基本信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="运单号：">
              <label>{{ form.no }}</label>
              <el-tag :type="orderStatus.type" size="mini" effect="plain">{{ orderStatus.label }}</el-tag>
            </el-form-item>
          </el-col>
          <el-col v-if="form.creatorId!=constants.otherCarId" :span="8">
            <el-form-item label="运输类型：" prop="lineType">
              <label v-if="form.lineType===0">直达</label>
              <label v-else-if="form.lineType===1">回头</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建人：">
              <label>{{ form.creator }}</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="纸厂单号" prop="pageNo">
              <label>{{ form.pageNo }}</label>
              <!-- <el-input v-model="form.pageNo" class="col-8" placeholder="纸厂单号" /> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-bg">
          <el-col :span="8">
            <el-form-item label="是否为空车单：">
              <el-tag v-if="form.isEmpty ==0 || form.isEmpty===null">否</el-tag>
              <el-tag v-else-if="form.isEmpty ==1" type="warning">是</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间：">
              <label>{{ form.createTime }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="更新时间：">
              <label>{{ form.updateTime }}</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.isEmpty!=1">
          <el-col v-if="form.status>0" :span="8">
            <el-form-item label="送货单(发)：" prop="deliveryVouchers">
              <el-image
                v-for="(item,index) in deliveryVouchers"
                :key="index"
                fit="contain"
                :src="item"
                :preview-src-list="deliveryVouchers"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="form.status>1" :span="8">
            <el-form-item label="送货单(收)：" prop="harvestVouchers">
              <el-image
                v-for="(item,index) in harvestVouchers"
                :key="index"
                fit="contain"
                :src="item"
                :preview-src-list="harvestVouchers"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="备注：" prop="remark">
              <label>{{ form.remark }}</label>
              <!-- <el-input
                v-model="form.remark"
                class="col-8"
                type="textarea"
                :rows="4"
                placeholder=""
                :disabled="true"
              />-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">车辆信息</el-divider>
        <!-- 自营 -->
        <div v-if="form.creatorId!=constants.otherCarId">
          <el-row>
            <el-col :span="8">
              <el-form-item label="驾驶员：" prop="originType">
                <label>{{ form.driverInfo.realName || "" }}</label>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系方式：" prop="originType">
                <label>{{ form.driverInfo.phone }}</label>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="车牌号：" prop="originType">
                <label>{{ form.carInfo.no || "" }}</label>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="挂车车牌号：" prop="originType">
                <label>{{ form.semitrailerNo || "" }}</label>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 外调车 -->
        <div v-else-if="form.creatorId==constants.otherCarId">
          <el-row>
            <el-col :span="8">
              <el-form-item label="驾驶员:" prop="originType">
                <label>{{ form.driverInfo.realName || "" }}</label>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="外调车联系方式：" prop="carPhone">
                <label>{{ form.carPhone || "" }}</label>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="外调车车牌：" prop="carNo">
                <label>{{ form.carNo || "" }}</label>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="外调半挂车车牌：" prop="semitrailerNo">
                <label>{{ form.semitrailerNo || "" }}</label>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-divider content-position="left">收货信息</el-divider>
        <el-row class="row-bg">
          <el-col :span="12">
            <el-form-item label="地址：">
              <label>{{ form.endArea }}</label>
              <label>{{ form.endAddress }}</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">发货信息</el-divider>
        <el-row class="row-bg">
          <el-col :span="12">
            <el-form-item label="地址：">
              <label>{{ form.startArea }}</label>
              <label>{{ form.startAddress }}</label>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <!-- 定价信息 -->
      <div v-if="form.status >2">
        <el-divider content-position="left">定价信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="委托方：" prop="locationInfo.name">
              <label>{{ form.locationInfo.name }}</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价：" prop="price">
              <label>{{ form.price }} 元</label>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运输费用：" prop="actualAmount">
              <label>{{ form.actualAmount }} 元</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="补充说明：" prop="msg">
          <el-input
            v-model="form.pricingMsg"
            class="col-8"
            type="textarea"
            :rows="4"
            placeholder
            :disabled="true"
          />
        </el-form-item>
      </div>
      <!-- 收款信息 -->
      <div v-if="form.status >3">
        <el-divider content-position="left">收款信息</el-divider>
        <el-form-item label="结算费用：" prop="actualAmount">
          <label>{{ form.actualAmount }} 元</label>
        </el-form-item>
        <!-- <el-form-item label="凭证：" prop="actualAmount">
          <el-image
            v-for="(item,index) in collectionVouchers"
            :key="index"
            fit="contain"
            :src="item"
            :preview-src-list="collectionVouchers"
          />
        </el-form-item>-->
      </div>

      <!-- 货品详情 -->
      <div class="details">
        <el-tabs value="orderProductList" type="border-card">
          <el-tab-pane label="货品明细" name="orderProductList">
            <div class="bg" />
            <table cellspacing="0" cellpadding="0">
              <thead>
                <tr>
                  <th class="index">#</th>
                  <th class="tool" valign="middle">
                    <el-button
                      class="btn"
                      size="mini"
                      icon="el-icon-plus"
                      :disabled="form.id!=null?true:false"
                      @click="plus"
                    />
                  </th>
                  <th>货品</th>
                  <th>采购量(吨)</th>
                  <th>是否为退货</th>
                  <!-- <th>单价/吨</th>
                  <th>小计</th>-->
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in form.orderProductList " :key="index">
                  <td class="index">{{ index+1 }}</td>
                  <td class="tool">
                    <el-button
                      class="btn"
                      icon="el-icon-minus"
                      :disabled="form.id!=null?true:false"
                      @click="minus(index)"
                    />
                  </td>
                  <td>
                    <el-form-item
                      :prop="'orderProductList.' + index + '.productId'"
                      :rules="page.rules.def"
                      label-width="0px"
                    >
                      <form-remote-select
                        v-model="item.productId"
                        :url="service.conf.api.get('wms').url+'/api/gds/product-info/map/2/'"
                        :disabled="form.id!=null?true:false"
                        @change="(current)=>bindProduct(current,item)"
                      />
                    </el-form-item>
                  </td>
                  <td>
                    <el-form-item
                      :prop="'orderProductList.' + index + '.weight'"
                      :rules="page.rules.num"
                      :disabled="form.status!=0"
                      label-width="0px"
                    >
                      <el-input-number
                        v-model="item.weight"
                        size="mini"
                        controls-position="right"
                        :precision="3"
                        :min="1"
                        :disabled="form.id!=null?true:false"
                        @change="(c,o)=>calItem(item)"
                      />
                    </el-form-item>
                  </td>
                  <td>
                    <el-form-item
                      :prop="'orderProductList.' + index + '.isReturn'"
                      :rules="page.rules.def"
                      label-width="0px"
                    >
                      <el-select
                        v-model="item.isReturn"
                        placeholder="请选择"
                        :disabled="form.id!=null?true:false"
                      >
                        <el-option
                          v-for="val in constants.isTrueFlase.values()"
                          :key="val.value"
                          :label="val.label"
                          :value="val.value"
                        />
                      </el-select>
                    </el-form-item>
                  </td>
                </tr>
              </tbody>
            </table>
          </el-tab-pane>
          <el-tab-pane v-if="form.id!=null" label="操作日志" name="log">
            <logs v-model="form.id" :datalogs="form.orderProcessList" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-form>
    <!-- 常用地址维护 -->
    <UsualAddress
      ref="myUsualAddress"
      request-url="/api/logistics/location/findLike"
      @handleAddress="handleAddress"
    />
    <!-- model -->
    <div v-if="form.id!=null" class="action">
      <pur-reject ref="reject" v-model="form.id" :self="self" />
      <pur-canceling ref="canceling" v-model="form.id" :self="self" />
      <pur-eceiving
        ref="evidenceImgs"
        v-model="form.id"
        :self="self"
        :btn-opt-type="btnOptType"
        :model-title="modelTitle"
      />
      <pur-pricing ref="pricing" v-model="form.id" :order-price="form.totalAmount" :self="self" />
    </div>
  </edit-layout>
</template>
<script>
import adminSupport from 'lola-admin-support-el'
import logs from './logs.vue'
import UsualAddress from '@/components/UsualAddress'
import PurReject from './components/reject.vue'
import PurCanceling from './components/canceling.vue'
import PurEceiving from './components/eceiving.vue'
import PurPricing from './components/pricing.vue'
export default {
  name: 'TransportEdit',
  components: {
    logs,
    UsualAddress,
    PurReject,
    PurCanceling,
    PurEceiving,
    PurPricing
  },
  mixins: [adminSupport.mixins.edit],
  data() {
    return {
      name: 'Transport',
      dialogVisible: false,
      self: null,
      btnOptType: '',
      modelTitle: '',

      deliveryVouchers: [], // 发货凭证图片
      harvestVouchers: [], // 收获凭证图片
      collectionVouchers: [] // 收款凭证图片
    }
  },
  computed: {
    isLogisticsDirector: function() {
      // 判断是否是物流主管登录
      const token = this.$store.getters.token
      const logisticsDirector = this.$store.state.settings.wmsConf.logistics
        .dutyId[0]
      return token.dutyId !== logisticsDirector
    },
    iswaiDiaoChe: function() {
      // 判断是否是外调车
      const token = this.$store.getters.token
      return parseInt(token.id) === this.$constants.otherCarId
    }
  },
  // 监听初始化数据
  watch: {
    form: function() {
      const arr = this.form.orderProcessList
      // console.log('监听表单初始化')
      if (!arr) return false
      arr.forEach(val => {
        if (val.flag === 1 && val.actionCode === 1) {
          // 发车
          this.deliveryVouchers = JSON.parse(val.credentials)
          console.log(val.credentials)
        } else if (val.flag === 1 && val.actionCode === 2) {
          // 收获
          this.harvestVouchers = JSON.parse(val.credentials)
        } else if (val.flag === 1 && val.actionCode === 3) {
          // 收款凭证图片
          this.form.pricingMsg = val.intro
        } else if (val.flag === 1 && val.actionCode === 4) {
          // 收款凭证图片
          this.collectionVouchers = JSON.parse(val.credentials)
        }
      })
      if (this.form.status === -1) this.page.tip = '订单已取消!'
    }
  },
  mounted() {
    this.init() // 初始化
    // console.log(111111)
    // console.log(this.$store.getters.token)
  },
  methods: {
    init() {
      const that = this
      this.self = that
      that.page.tip = '请认真核对车辆信息/发货信息等相关选项,创建后禁止修改!'
      that.page.ids.push(this.$route.params.no) // 页面主参数赋值
      that.loadData() // 加载数据
    },
    appendForm() {
      this.orderStatus = this.$constants.logisticsOrderStatus.get(
        this.form.status
      )
    },
    buildForm() {
      return true
    },
    // 添加明细
    plus() {
      // this.form.orderProductList.push({ money: 0, weight: null, price: null })
      this.form.orderProductList.push({ weight: null })
      console.log(this.form.orderProductList)
    },
    // 删除明细
    minus(index) {
      this.form.orderProductList.splice(index, 1)
    },
    bindProduct(current, item) {
      item.productNo = current.val
      item.name = current.name
    },
    // 计算小计
    calItem(item) {
      console.log(item)
      // item.money = item.weight * item.price
      // this.cal();
    },
    cal() {
      // 计算订单总额
      let weight = 0 // 订单采购量
      const totalAmount = 0 // 采购总金额
      this.form.orderProductList.forEach(item => {
        weight += item.weight
        // totalAmount += item.money
      })
      this.form.amount = weight
      this.form.totalAmount = totalAmount
    },
    setAreaStart(val) {
      this.form.startArea = val
    },
    setAreaEnd(val) {
      this.form.endArea = val
    },
    // 常用地址管理
    UsualAddressUesd(type) {
      this.$refs['myUsualAddress'].modelShow(type)
    },
    // 监听常用地址组件选择
    handleAddress(res) {
      console.log(res)
      if (res.locationType === 'start') {
        this.form.startArea = res.area
        this.form.startAddress = res.address
        this.form.startAreaIds = res.areaIds
      } else if (res.locationType === 'end') {
        this.form.endArea = res.area
        this.form.endAddress = res.address
        this.form.endAreaIds = res.areaIds
      }
    },
    // 监听车辆选择
    selectCar(val) {
      console.log(val)
      this.form.carNo = val.name
    },

    // 重写按钮方法
    buildOtherBtn(item, btn) {
      switch (item.code) {
        case 'm5142': // 删除
          btn.disable = this.form.status < 1 && this.form.id !== null
          btn.type = 'warning'
          break
        // case 'm5145': // 审核
        //   btn.disable = this.form.status === 0 && this.form.id !== null
        //   btn.type = 'info'
        //   btn.opt = 'checking'
        //   break
        case 'm5146': // 发货
          btn.disable = this.form.status === 0 && this.form.id !== null
          btn.type = ''
          btn.opt = 'delivery'
          break
        case 'm5147': // 已发车，待签收
          btn.disable = this.form.status === 1 && this.form.id !== null
          btn.type = 'success'
          btn.opt = 'harvest'
          break
        case 'm5148': // 已签收，待定价
          btn.disable =
            this.form.status === 2 &&
            this.form.id !== null &&
            this.form.isEmpty !== 1
          btn.type = ''
          btn.opt = 'pricing'
          break
        // case 'm5149': // 核算
        //   btn.disable = this.form.status === 3 && this.form.id !== null
        //   btn.type = ''
        //   btn.opt = 'accounting'
        //   break
        case 'm51491': // 取消
          btn.disable =
            this.form.status < 1 &&
            this.form.id !== null &&
            this.form.status !== -1
          btn.type = 'danger'
          btn.opt = 'canceling'
          break
        case 'm51492': // 已定价，待收款
          btn.disable =
            this.form.status === 3 &&
            this.form.id !== null &&
            this.form.isEmpty !== 1
          btn.type = ''
          btn.opt = 'settlement'
          break
        case 'm51493': // 驳回
          btn.disable =
            this.form.status < 4 &&
            this.form.id !== null &&
            this.form.status > 0 &&
            this.form.status !== 2 &&
            this.form.isEmpty !== 1
          btn.type = 'warning'
          btn.opt = 'rejected'
          break
        case 'm51494': // 归档
          btn.disable =
            this.form.status === 4 &&
            this.form.id !== null &&
            this.form.isArchive === 0
          btn.type = ''
          btn.opt = 'archive'
          break
      }
    },
    // 审核
    checking() {
      console.log()
      const that = this
      const url = that.$http.conf.api.get('wms').url + '/api/logistics/order/audit'
      const params = { orderId: this.form.id }
      this.$confirm('是否审核通过该运输单?', '提示', {
        type: 'warning'
      }).then(() => {
        that.$http.post(url, params).then(function(rsp) {
          if (rsp.code === 200) {
            that.$message.success('操作成功!')
            that.form.status = 1
            that.init()
          } else {
            that.$message.error(rsp.message)
          }
        })
      })
    },
    // 发货
    delivery() {
      const that = this
      that.btnOptType = 'delivery'
      that.modelTitle = '确认发货上传凭证'
      that.$refs.evidenceImgs.show('delivery')
    },
    // 收获
    harvest() {
      const that = this
      that.btnOptType = 'harvest'
      that.modelTitle = '确认收货上传凭证'
      that.$refs.evidenceImgs.show('harvest')
    },
    // 定价
    pricing(e) {
      // console.log(this.form)
      this.$refs.pricing.show('pricing', this.form)
    },
    // 核算
    accounting() {
      this.$refs.pricing.show('accounting', this.form)
    },
    // 结算
    settlement() {
      const that = this
      // that.btnOptType = 'settlement'
      // that.modelTitle = '确认已结算上传凭证'
      // that.$refs.evidenceImgs.show('settlement')

      const url =
        that.$http.conf.api.get('wms').url + '/api/logistics/order/complete'
      const params = { orderId: this.form.id }
      this.$confirm('确认已结算该运输单?', '提示', {
        type: 'success'
      }).then(() => {
        that.$http.post(url, params).then(function(rsp) {
          if (rsp.code === 200) {
            that.$message.success('操作成功!')
            that.form.status = 1
            that.init()
          } else {
            that.$message.error(rsp.message)
          }
        })
      })
    },
    // 归档
    archive() {
      const that = this
      // that.btnOptType = 'settlement'
      // that.modelTitle = '确认已结算上传凭证'
      // that.$refs.evidenceImgs.show('settlement')

      const url =
        that.$http.conf.api.get('wms').url + '/api/logistics/order/archive'
      const params = { orderId: this.form.id }
      this.$confirm('确认归档?', '提示', {
        type: 'success'
      }).then(() => {
        that.$http.post(url, params).then(function(rsp) {
          if (rsp.code === 200) {
            that.$message.success('操作成功!')
            that.form.isArchive = 1
            that.init()
          } else {
            that.$message.error(rsp.message)
          }
        })
      })
    },
    rejected() {
      // 订单驳回
      this.$refs.reject.show()
    },
    canceling() {
      // 取消订单
      this.$refs.canceling.show()
    },

    // 驾驶员切换
    driverChange(val) {
      console.log(val)
      // console.log(this.form.carId)
      this.form.carId = val.val
    }
  }
}
</script>
